﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(CrossSection))]
public class CrossSectionEditor : E_ShowButtons<CrossSection> { }
#endif
[ExecuteInEditMode]
public class CrossSection : MonoSingleton<CrossSection>, IFind
{
    public int vertsCount;
    public GameObject prefab;
    public Material mirror;
    public float space = 0.5f;
    string IFind.findName { get { return "Container"; } }
    private Transform _container;
    public bool mirrorImmed;
    public float combineDist = 0.1f;
    [ShowButton]
    void GeneratePoints()
    {
        ComTool.ClearChildren(this.Find());
        for (int i = 0; i < vertsCount; i++)
        {
            var go = Instantiate(prefab, this.Find());
            go.transform.localPosition = Vector3.zero;
            go.transform.SetLocalPosX(i * space);
            go.name = "p " + i.ToString();
            go.SetActive(true);
        }
    }
    [ShowButton]
    void MirrorPoints()
    {
        ComTool.ClearChildren(this.Find(), "m");
        int i = 0;
        foreach (var t in this.Find().GetChildrens())
        {
            if (Mathf.Abs(t.localPosition.x) < combineDist) t.SetLocalPosX(0);
            var go = Instantiate(prefab, this.Find());
            go.GetComponent<Renderer>().sharedMaterial = mirror;
            go.transform.localPosition = t.localPosition.MirrorX();
            go.name = "m " + i.ToString();
            go.SetActive(true);
            i++;
        }
    }
    void Update()
    {
        var t = Selection.activeTransform;
        if (t != null)
        {
            var p = t.parent;
            if (mirrorImmed && p == this.Find() && t.name.StartsWith("p"))
                MirrorPoints();
        }
    }
}
